<template>
  <div class="inventory-alert">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称"
          clearable
          style="width: 300px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 库存预警表格 -->
    <el-table
        :data="paginatedData"
        border
        stripe
        style="width: 100%"
        :row-class-name="rowClassName"
    >
      <el-table-column prop="name" label="商品名称" width="220" />
      <el-table-column prop="currentStock" label="当前库存" width="120" align="center" />
      <el-table-column prop="safetyStock" label="安全库存" width="120" align="center" />

      <el-table-column label="紧急程度" width="130" align="center">
        <template #default="{ row }">
          <el-tag
              :type="getAlertLevel(row).type"
              effect="dark"
          >
            {{ getAlertLevel(row).text }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="lastUpdated" label="最后更新时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.lastUpdated) }}
        </template>
      </el-table-column>
      <!-- 新增操作列 -->
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              link
              @click="openSafetyStockDialog(row)"
          >
            设置安全库存
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 安全库存设置对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="设置安全库存"
        width="500px"
    >
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" disabled />
        </el-form-item>

        <el-form-item label="安全库存" prop="safetyStock">
          <el-input-number
              v-model="form.safetyStock"
              :min="0"
              :precision="0"
              controls-position="right"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="submitting"
            @click="submitSafetyStock"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="filteredData.length"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          background
      />
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue'
import { Search } from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
import {changeSafetyStock, getAllStockInfo} from "@/api/auth.js";
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref()
const editingItem = ref(null)
// 模拟数据
const rawData = ref([
  {
    id:1,
    name: '笔记本电脑',
    currentStock: 15,
    safetyStock: 20,
    lastUpdated: '2024-03-15T09:30:00'
  },
  {
    id:2,
    name: '手机',
    currentStock: 50,
    safetyStock: 30,
    lastUpdated: '2024-03-15T10:15:00'
  },
  {
    id:3,
    name: '显示器',
    currentStock: 8,
    safetyStock: 15,
    lastUpdated: '2024-03-15T11:00:00'
  }
])

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10
})
const initData=async ()=>{
  try {
    const res=await getAllStockInfo()
    if(res.code===200){
      rawData.value=res.data
    }else {
      console.log(res.message)
    }
  }catch (e){
    ElMessage.error(e)
  }


}
onMounted(()=>{
  initData()
})
// 搜索关键词
const searchKeyword = ref('')

// 过滤数据
const filteredData = computed(() => {
  return rawData.value.filter(item =>
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 分页数据
const paginatedData = computed(() => {
  const start = (pagination.current - 1) * pagination.size
  return filteredData.value.slice(start, start + pagination.size)
})

// 预警等级判断
const getAlertLevel = (row) => {
  const ratio = row.currentStock / row.safetyStock
  if (row.currentStock*0.95 <= row.safetyStock ) {
    return { type: 'danger', text: '紧急缺货' }
  } else if (row.currentStock*0.75 <= row.safetyStock) {
    return { type: 'warning', text: '库存不足' }
  }
  return { type: 'success', text: '库存正常' }
}
const rules = {
  safetyStock: [
    { required: true, message: '必须输入安全库存值' },
    {
      validator: (_, value, callback) => {
        if (value < 0) return callback(new Error('不能小于0'))
        if (!Number.isInteger(value)) return callback(new Error('必须为整数'))
        callback()
      }
    }
  ]
}
const form = reactive({
  id:0,
  name: '',
  safetyStock: 0
})
// 打开设置对话框
const openSafetyStockDialog = (row) => {
  editingItem.value = row
  form.name = row.name
  form.safetyStock = row.safetyStock
  form.id = row.id
  dialogVisible.value = true
}
const submitSafetyStock = async () => {
  try {
    const res=await changeSafetyStock(form)
    if(res.code===200){
      ElMessage.success(res.message)

    }else {
      ElMessage.error(res.message)
    }


  } catch (err) {
    ElMessage.error(err.message || '设置失败')
  } finally {
    submitting.value = false
  }
  await initData()
  dialogVisible.value = false
}

// 时间格式化
const formatTime = (timeString) => {
  return new Date(timeString).toLocaleString()
}

// 行样式
const rowClassName = ({ row }) => {
  const level = getAlertLevel(row).type
  return level === 'danger' ? 'warning-row' : ''
}
</script>

<style scoped>
.inventory-alert {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 预警行样式 */
:deep(.warning-row) {
  --el-table-tr-bg-color: var(--el-color-danger-light-9);
}

.el-tag {
  font-weight: 500;
  letter-spacing: 0.5px;
}
</style>